package com.wonyesoft.wuliu.acticity;

import httptools.HttpJsonTool;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tools.CheckVersion;
import tools.DownLoadAPP;
import tools.LogFileFind;
import tools.SD_Finder;

import View.InPutDialog;
import View.InPutDialog.getUserIntent;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.Vibrator;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.platform.comapi.map.p;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.wonyesoft.wuliu.AppContent;
import com.wonyesoft.wuliu.AppContent.GetBaiDuPush;
import com.wonyesoft.wuliu.AppContent.getGpsAddress;

import com.wonyesoft.wuliu.R;
import com.wonyesoft.wuliu.acticity.base.BaseActivity;
import com.wonyesoft.wuliu.acticity.order.OrdersActivity;
import com.wonyesoft.wuliu.acticity.view.cpbutton.SlideImageLayout;
import com.wonyesoft.wuliu.api.GagApi;


public class TestAcivity extends BaseActivity implements OnClickListener {

	// 滑动图片的集合
	private ArrayList<View> imagePageViews = null;

	private ViewPager viewPager = null;

	// 百度消息推送ID
	private String channelId;
	private String messagepushuserId;

	// 当前ViewPager索引
	private int pageIndex = 0;

	// 包含圆点图片的View
//	private ViewGroup imageCircleView = null;

	private ImageView[] imageCircleViews = null;

	private SlideImageLayout slideLayout = null;

	List<TextView> titleViews = new ArrayList<TextView>();

	Handler handler;

	private RequestParams params;

	public static Gson gson = new Gson();

	private HttpUtils http = new HttpUtils();

	private AppContent app;

	private PreferencesCookieStore preferencesCookieStore;

	private SharedPreferences share;

	private String key = "UserInfo";

	// 更新自动广告
	private static final int H_UPDATE_AUTO_SELECTED = 1;

	private static final int H_RESET_LIST = 2;

	private static final int H_LOAD_DATA = 3;

	boolean adAuto = true;

	// 广告正在滑动
	boolean adScrolling = false;

//	private TextView lbsico;

	private List<String[]> types;

	public static String[] imgsUrl = { null, null, null, null, };

	private LocationClient mLocationClient;
	private LocationMode tempMode = LocationMode.Hight_Accuracy;
	private String tempcoor = "bd09ll";
	public Vibrator mVibrator;
//	private LinearLayout lbsview;
	private ImageView btn_number, btn_english, btn_chinese;
	private ImageView iv_game, iv_record, iv_rank;
	private ImageView iv_contact, iv_about, iv_about_me;
	private LinearLayout myjijian, chandan, jidan, jichu, fuwu, mygongju;
	private Button grid_send, grid_search, grid_coming, grid_out, grid_service,
			grid_tools;

	// 小雨grid
	List<Map<String, Object>> glist;

	// int[] img = { R.drawable.send_express1, R.drawable.search_express,
	// R.drawable.coming_express, R.drawable.out_express,
	// R.drawable.service, R.drawable.common_tools };
	int[] img = { R.drawable.send_express1, R.drawable.out_express,
			R.drawable.service, R.drawable.common_tools, R.drawable.user_myinfo };

	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.all_home_new_activity);
		app = (AppContent) getApplication();
		app.addActivity(this);
		preferencesCookieStore = app.getPreferencesCookieStore();
//		lbsview = (LinearLayout) findViewById(R.id.lbsview);
//		lbsview.setOnClickListener(this);
		baidulbs();
		GetPushID();
		// inOnclick();
//		initHandler();
//		InitHeadAd();
		// xiaoyu();
//		adThread.start();
//		lbsico = (TextView) findViewById(R.id.lbsico);
//		lbsico.setText(app.adrr);
		inIClick();
		checkVersion();
		checkLogAndUpload();
	//	checkBaiduPushEable();
		//设置gps callback数值
//		setGpsCallback();
	}

	private void setGpsCallback(){
		app.setGpsCallback(new getGpsAddress() {
			
			@Override
			public void getlocation(String location) {
				// TODO Auto-generated method stub
//				lbsico.setText(location);
			}
		});
	
	}
	
	
	private void baidulbs() {

		mLocationClient = app.mLocationClient;
		InitLocation();
		mLocationClient.start();

	}

	private void InitLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(tempMode);// 设置定位模式
		option.setCoorType(tempcoor);// 返回的定位结果是百度经纬度，默认值gcj02
		int span = AppContent.LOCATION_TIME;
		option.setScanSpan(span);// 设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);

	}

	private void inIClick() {
		CEHZonClick click = new CEHZonClick();
		ImageView mycargo_activity_image = (ImageView) findViewById(R.id.mycargo_activity_image);
		ImageView addcargo_activityimageView3 = (ImageView) findViewById(R.id.addcargo_activityimageView3);
		ImageView seting_activityimageView4 = (ImageView) findViewById(R.id.seting_activityimageView4);
		ImageView myserfelsimageView5 = (ImageView) findViewById(R.id.myserfelsimageView5);
		ImageView tariffimageView6 = (ImageView) findViewById(R.id.tariffimageView6);
		
		
		TextView mycargo_activity_text = (TextView) findViewById(R.id.mycargo_activity_text);
		TextView addcargo_activitytextView2 = (TextView) findViewById(R.id.addcargo_activitytextView2);
		TextView seting_activitytextView3 = (TextView) findViewById(R.id.seting_activitytextView3);
		TextView myserfelstextView4 = (TextView) findViewById(R.id.myserfelstextView4);
		TextView tarifftextView5 = (TextView) findViewById(R.id.tarifftextView5);
		
		
		mycargo_activity_image.setOnClickListener(click);
		addcargo_activityimageView3.setOnClickListener(click);
		seting_activityimageView4.setOnClickListener(click);
		myserfelsimageView5.setOnClickListener(click);
		tariffimageView6.setOnClickListener(click);
		mycargo_activity_text.setOnClickListener(click);
		addcargo_activitytextView2.setOnClickListener(click);
		seting_activitytextView3.setOnClickListener(click);
		myserfelstextView4.setOnClickListener(click);
		tarifftextView5.setOnClickListener(click);

	}

	private class CEHZonClick implements OnClickListener {

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.mycargo_activity_image:
				openActivity(ChoseCarTypeActivity.class);
				break;
			case R.id.addcargo_activityimageView3:
				openActivity(OrdersActivity.class);
				break;
			case R.id.seting_activityimageView4:
				openActivity(SettingActivity.class);
				break;
			case R.id.myserfelsimageView5:
				openActivity(UserInfoActivity.class);
				break;
			case R.id.tarifftextView5:
				openActivity(ZiFeiActivity.class);
				break;
				
				//textview
			case R.id.mycargo_activity_text:
				openActivity(ChoseCarTypeActivity.class);
				break;
			case R.id.addcargo_activitytextView2:
				openActivity(OrdersActivity.class);
				break;
			case R.id.seting_activitytextView3:
				openActivity(SettingActivity.class);
				break;
			case R.id.myserfelstextView4:
				openActivity(UserInfoActivity.class);
				break;
			case R.id.tariffimageView6:
				openActivity(ZiFeiActivity.class);
				break;
			default:
				break;
			}
		}

	}

	private void xiaoyu() {
		GridView gridView;
		SimpleAdapter gridadapter;

		gridView = (GridView) findViewById(R.id.main_grid);
		glist = new ArrayList<Map<String, Object>>();
		gridadapter = new SimpleAdapter(this, getData(), R.layout.grid_content,
				new String[] { "img", "text" }, new int[] { R.id.main_grid_img,
						R.id.main_grid_text });
		gridView.setAdapter(gridadapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int idx,
					long arg3) {
				// TODO Auto-generated method stub
				switch (img[idx]) {
				case R.drawable.send_express1:
					// openActivity(AddCargoActivity.class);
					openActivity(ChoseCarTypeActivity.class);
					break;
				case R.drawable.search_express:
					// openActivity(UserSearchListActivity.class);
					break;
				case R.drawable.user_myinfo:
					// isLogin(AddCargoQuickActivity.class);
					openActivity(UserInfoActivity.class);
					break;
				case R.drawable.out_express:
					// openActivity(OrderListsActivity.class);
					openActivity(OrdersActivity.class);
					break;
				case R.drawable.service:
					openActivity(ZiFeiActivity.class);
					break;
				case R.drawable.common_tools:
					openActivity(SettingActivity.class);
					break;

				default:
					break;
				}

			}

		});

	}

	private List<Map<String, Object>> getData() {

		String[] iname = { "我要下单", "我寄出的", "资费详情", "设      置 ", "我的信息" };

		for (int i = 0; i < img.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("img", img[i]);
			map.put("text", iname[i]);
			glist.add(map);

		}
		return glist;

	}

	// // 绑定首页
	private void inOnclick() {
		// TODO Auto-generated method stub
		myjijian = (LinearLayout) findViewById(R.id.myjijian);
		chandan = (LinearLayout) findViewById(R.id.chadan);
		jidan = (LinearLayout) findViewById(R.id.jidan);
		jichu = (LinearLayout) findViewById(R.id.jichu);
		fuwu = (LinearLayout) findViewById(R.id.fuwu);
		mygongju = (LinearLayout) findViewById(R.id.mygongju);
		grid_send = (Button) findViewById(R.id.grid_send);
		grid_search = (Button) findViewById(R.id.grid_search);
		grid_coming = (Button) findViewById(R.id.grid_coming);
		grid_out = (Button) findViewById(R.id.grid_out);
		grid_service = (Button) findViewById(R.id.grid_service);
		grid_tools = (Button) findViewById(R.id.grid_tools);
		grid_send.setOnClickListener(this);
		grid_search.setOnClickListener(this);
		grid_coming.setOnClickListener(this);
		grid_out.setOnClickListener(this);
		grid_search.setOnClickListener(this);
		grid_tools.setOnClickListener(this);
		myjijian.setOnClickListener(this);
		chandan.setOnClickListener(this);
		jidan.setOnClickListener(this);
		jichu.setOnClickListener(this);
		fuwu.setOnClickListener(this);
		mygongju.setOnClickListener(this);
	}

	// 为首页内图标绑定点击方法
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.myjijian:
		case R.id.grid_send:
			isLogin(UserAddListActivity.class);
			// openActivity();
			break;
		case R.id.chadan:
		case R.id.grid_search:
			openActivity(UserSearchListActivity.class);
			break;
		case R.id.jidan:
		case R.id.grid_coming:
			isLogin(OrderListsActivity.class);
			break;
		case R.id.jichu:
		case R.id.grid_out:
			isLogin(OrderListsActivity.class);
			break;
		case R.id.fuwu:
		case R.id.grid_service:
			openActivity(ZiFeiActivity.class);
			// showLongToast("即将开放该功能...");
			break;
		case R.id.mygongju:
		case R.id.grid_tools:
			// showLongToast("即将开放该功能...");
			openActivity(SettingActivity.class);
			break;
		case R.id.lbsico:
		case R.id.lbsview:
//			lbsico.setText(app.adrr);
//			mLocationClient.stop();
			break;

		default:
			break;
		}
	}

	private void initHandler() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case H_UPDATE_AUTO_SELECTED:
					updateAddSelecedStatus();
					viewPager.setCurrentItem(pageIndex);
					break;
				case H_RESET_LIST:
					break;
				case H_LOAD_DATA:
					break;
				default:
					break;
				}
			}
		};
	}

	Thread adThread = new Thread() {
		public void run() {
			while (adAuto) {
				try {
					sleep(6000);
					if (adScrolling == false) {
						pageIndex++;
						if (pageIndex > imagePageViews.size() - 1)
							pageIndex = 0;
						handler.sendEmptyMessage(H_UPDATE_AUTO_SELECTED);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
	};

	/**
	 * 加载头部广告
	 */
	private void InitHeadAd() {
		// 滑动图片区域
		imagePageViews = new ArrayList<View>();
		viewPager = (ViewPager) this.findViewById(R.id.image_slide_page);
		// 圆点图片区域
		int length = imgsUrl.length;
//		imageCircleViews = new ImageView[length];
//		imageCircleView = (ViewGroup) this
//				.findViewById(R.id.layout_circle_images);
		slideLayout = new SlideImageLayout(this);
		slideLayout.setCircleImageLayout(length);
		for (int i = 0; i < length; i++) {
			int defId = R.drawable.a01;
			switch (i) {
			case 1:
				defId = R.drawable.a02;
				break;
			case 2:
				defId = R.drawable.a03;
				break;
			case 3:
				defId = R.drawable.a04;
				break;
			}
			View ImageView = slideLayout.getSlideImageLayout(imgsUrl[i], i,
					defId);
			imagePageViews.add(ImageView);
			imageCircleViews[i] = slideLayout.getCircleImageLayout(i);
//			imageCircleView.addView(slideLayout.getLinearLayout(
//					imageCircleViews[i], 10, 10));
		}
		viewPager.setAdapter(new SlideImageAdapter());
		viewPager.setOnPageChangeListener(new ImagePageChangeListener());
	}

	// 滑动图片数据适配器
	private class SlideImageAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			// adScrolling = true;
			return imagePageViews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;

		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(imagePageViews.get(arg1));
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imagePageViews.get(arg1));

			return imagePageViews.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

	// 滑动页面更改事件监听器
	private class ImagePageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int index) {
			pageIndex = index;
			updateAddSelecedStatus();
		}
	}

	/**
	 * 更新广告选项中状态
	 */
	private void updateAddSelecedStatus() {
		slideLayout.setPageIndex(pageIndex);
		for (int i = 0; i < imageCircleViews.length; i++) {
			if (i == pageIndex) {
				imageCircleViews[pageIndex]
						.setBackgroundResource(R.drawable.page_indicator_focused);
			} else {
				imageCircleViews[i]
						.setBackgroundResource(R.drawable.page_indicator_unfocused);
			}
		}
	}

	/**
	 * 上传messagepushuserId和channelId
	 */
	private void GetPushID() {
		Log.e("获得的channelId", "");
		if (app.channelId != null && app.channelId.length() > 0) {
			Log.v("获得的channelId", app.channelId);
//			if (app.messagepushuserId != null
//					&& app.messagepushuserId.length() > 0) {
				UpDataBAIDU_IDtoServer(app.channelId, app.messagepushuserId);
//			}
		} else {

			app.SetGetBaiDuPush(new GetBaiDuPush() {

				@Override
				public void GetMessage(String channelId_app, String userId_app) {
					// TODO Auto-generated method stub
					// channelId,String messagepushuserId
					Log.v("获得的channelId", app.channelId);
					UpDataBAIDU_IDtoServer(channelId_app, userId_app);
				}
			});
		}

	}

	
	
	
	
	/**
	 * 获得的百度推送ID给服务器
	 */
	private void UpDataBAIDU_IDtoServer(String channelId_app, String userId_app) {
		HashMap<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("channelid", channelId_app);
		dataMap.put("userid", "null");
		dataMap.put("cargoownerid", app.userId);
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);

		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
			}
		});
		httpJsonTool.StartWork(dataMap, GagApi.PUSH_UP_DATA_URL, null, null);
		if (app.userinfobeen != null) {

		} else {
			Intent intent = new Intent(this, UserLoginActivity.class);
			startActivity(intent);
		}
	}

	/**
	 * 
	 * @Title: checkLogAndUpload
	 * @Description: TODO(检查log并且上传)
	 * @param 参数说明
	 * @return void 返回类型
	 * @throws
	 */
	private void checkLogAndUpload() {
		String rootpath = SD_Finder.GetPaht();
		if (rootpath != null && rootpath.length() > 0) {
			String path =  rootpath+GagApi.TCZH_File ;
			File folder = new File(path);
			List<String> allLogfile = new ArrayList<String>();
			LogFileFind filter = new LogFileFind("log");
			String[] logfilenames = folder.list(filter);
			if (logfilenames!=null&&logfilenames.length > 0) {

				allLogfile.addAll(Arrays.asList(logfilenames));
				// 计算有多少个文件
				// int fileSum=allLogfile.size();
				for (int i = 0; i < allLogfile.size(); i++) {
					upLogFIleUpload(path+"/"+allLogfile.get(i));
				}
			}
		}

	}

	private void upLogFIleUpload(final String path) {
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.setLogHandle(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 1) {
					File file = new File(path);
					file.delete();
				}
			}
		});
		httpJsonTool.UpLoadFile(path);
	}
	
	
	private void checkVersion(){
		CheckVersion.check(this, new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what==1) {
					InPutDialog inPutDialog=new InPutDialog(TestAcivity.this, "版本更新", "有新的版本更新","下载","取消");
					inPutDialog.setGetUserIntent(new getUserIntent() {

						@Override
						public void getUserIntentInfo() {
							// TODO Auto-generated method stub
							Intent intents = new Intent();
							intents.setClass(TestAcivity.this,
									DownLoadAPP.class);
							String root = SD_Finder.GetPaht();
							if (root != null && root.length() > 0) {
								intents.putExtra("path", root);
								startService(intents);
							
							} else {								
								Toast.makeText(TestAcivity.this,
										"未找到SD卡，无法下载", Toast.LENGTH_LONG)
										.show();
							}
						}
					});
					inPutDialog.getCheckDialog(false);
				}
			}
		});		
	}
	
	/**
	 * 检查百度推送是否开启
	 */
//	private void checkBaiduPushEable(){
//		if (!(PushManager.isPushEnabled(getApplicationContext()))) {
//			PushManager.startWork(getApplicationContext(),
//					PushConstants.LOGIN_TYPE_API_KEY, "Gv9FASP1Ob4KLLPNC0iotuVg");
//
//			Log.e("百度推送没有启动", "百度推送没有启动");
//		}else {
//			Log.e("百度推送已经启动", "百度推送已经启动");
//			PushManager.startWork(getApplicationContext(),
//					PushConstants.LOGIN_TYPE_API_KEY, "Gv9FASP1Ob4KLLPNC0iotuVg");
//		}		
//	}
	
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
///		checkBaiduPushEable();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		checkBaiduPushEable();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mLocationClient.stop();
	}

}
